<?php

namespace App\Admin\Grid\BatchAction;

use App\Models\DyQc;
use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;
use App\Actions\DyHookAction;
use App\Logics\AdminOperationLogLogic;
use App\Models\AdminUser;
use App\Models\Config;
use App\Models\DyDwXref;
use App\Policies\Admin\AdminPolicy;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BatchDelete extends BatchAction
{
    protected $modelClass;
    protected $table;

    // 注意action的构造方法参数一定要给默认值
    public function __construct($title = null, $modelClass = null, $table = null)
    {
        $this->title = $title;
        $this->modelClass = $modelClass;
        $this->table = $table;
    }

    // 确认弹窗信息
    public function confirm()
    {
        return '您确定要删除已选中的数据吗？';
    }

    // 处理请求
    public function handle(Request $request)
    {
        // 获取选中的文章ID数组
        $keys = $this->getKey();
        // 获取请求参数
        $table = $request->get('table');
        $modelClass = $request->get('modelClass');
        $admin_user = AdminUser::find(Admin::user()->id);

        foreach ($keys as $id) {
            $relation_row = $modelClass::query()->where('id', $id)->first();
            if (!$relation_row) {
                return $this->response()->error('记录不存在');
            }
            if (!AdminPolicy::make($relation_row, $admin_user)->can_delete()) {
                return $this->response()->error('无权删除' . $request->desc);
            }
            if (!$admin_user->isSuperManger()) {
                # 非超级管理员，仅需要删除本条数据
                DB::table($table)->where('id', $id)->delete();
            } else {
                # 超级管理员，删除所有身份照号相同的数据
                if ($relation_row->sfz) {
                    # 有身份证号码
                    DB::table($table)->where('sfz', $relation_row->sfz)->delete();
                } else {
                    # 没有身份证号码
                    DB::table($table)->where('id', $id)->delete();
                }
            }
            DyHookAction::make()->afterDelete($relation_row, $table);
            try {
                $title = $modelClass::NAME;
                $desc = '';
                $desc .= isset($relation_row->name) ? "姓名：{$relation_row->name}" : "";
                $desc .= isset($relation_row->sfz) ? "身份证：{$relation_row->sfz}" : "";
                AdminOperationLogLogic::make(null, $admin_user)->delete(["删除{$title}{$desc}"])->log();
            } catch (\Throwable $th) {
            }
        }

        $message = '删除成功';

        return $this->response()->success($message)->refresh();
    }

    // 设置请求参数
    public function parameters()
    {
        return [
            'table' => $this->table,
            'modelClass' => $this->modelClass,
        ];
    }
}